<template>
	<view class="container">
		<!--tabbar-->
		<view class="tui-operation tui-chat-operation">
			<view class='tui-right-flex tui-input-box'>
				<!-- <view hover-class="tui-opcity" :hover-stay-time="150" class="tui-voice">
					<tui-icon name="voice" :size="34" color='#333'></tui-icon>
				</view> -->
				<input class="tui-chat-input" v-model="inputValue" placeholder="输入你想说的"></input>
			</view>
			<!-- <view hover-class="tui-opcity" :hover-stay-time="150">
				<tui-icon name="imface" :size="26" color='#333'></tui-icon>
			</view> -->
			<view hover-class="tui-opcity" :hover-stay-time="150" class="tui-pr" @tap="send">
				<tui-icon name="send" :ize="30" color='#333'></tui-icon>
			</view>
		</view>
		<!--tabbar-->
		<view class="tui-chat-content">
			<tui-loadmore :visible="loadding" :index="3" type="primary" text=" "></tui-loadmore>
			
			<view v-if="isNoMore && memberBaseTo.headPic==undefined" class="tui-label">~对方未回复只能发3条消息~</view>
			<view v-if="isNoMore && memberBaseTo.headPic!=undefined" class="tui-label">~没有更多记录了~</view>
			<view v-if="!isNoMore" class="tui-label">~下拉获取更多~</view>
			<view class="tui-chat-center" v-if="dataList.length>0">{{dataList[0].sendTime}}</view>
			<block v-for="(item, index) in dataList" :key="index">
				<block v-if="item.memberIdTo==memberIdTo">
					<view class="tui-chat-right">
						<view class="tui-chatbox tui-chatbox-right">{{item.content}}</view>
						<image lazy-load="true" :src="$cdn.appAvatar+headPic" class="tui-user-pic tui-left"></image>
					</view>
				</block>
				<block v-else>
					<view class="tui-chat-left">
						<image lazy-load="true" :src="$cdn.appAvatar+item.memberBase.headPic" class="tui-user-pic tui-right"></image>
						<view class="tui-chatbox tui-chatbox-left">{{item.content}}</view>
					</view>
				</block>
				
			</block>
			
		</view>
		<view class="tui-safearea-bottom"></view>
	</view>
</template>

<script>
	import { mapState, mapMutations, mapActions } from 'vuex';
	import tuiIcon from "@/components/icon/icon"
	import tuiBadge from "@/components/badge/badge"
	import tuiLoadmore from "@/components/loadmore/loadmore"
	export default {
		computed: mapState(['headPic','userName']),
		components:{
			tuiIcon,
			tuiBadge,
			tuiLoadmore
		},
		data() {
			return {
				$cdn: this.$cdn,
				// 分页必备参数
				pageIndex: 1,
				loadding: false,
				dataList:[],
				memberIdTo:'',
				isNoMore:false,
				
				// websocket连接对象
				socketTask:{},
				inputValue:'',
				memberBaseTo:{}
			}
		},
		onLoad: function(options) {
			uni.pageScrollTo({
				scrollTop: 90000000
			});
			this.memberIdTo=options.memberIdTo;
			let userName=options.userName;
			if(userName!=undefined && userName!=''){
				uni.setNavigationBarTitle({
					title: '与'+userName+' 的消息'
				});
			}
			if(this.memberIdTo==undefined || this.memberIdTo==''){
				this.tui.toast('未获取到对方UID');
			}else{
			this.pageData(1, false,{memberIdTo:this.memberIdTo});
			// 打开websocket链接
			this.openWebSocket();
			}
			console.log('memberBaseTo='+JSON.stringify(this.memberBaseTo));
		},
		methods: {
		// 获取
		pageData(pageIndex, isRefresh, postData) {
			this.tui
				.request(this.$api.pageToChat + '?pageNum=' + pageIndex + '&pageSize=' + this.$api.pageSize, postData, 'POST', false, pageIndex == 1 && !isRefresh ? false : true)
				.then(res => {
					if (res.code == 0) {
						if (pageIndex == 1) {
							this.dataList = res.data.rows;
							
							// 取对方memberbase对象
							for (var i = 0; i < res.data.rows.length; i++) {
								if(res.data.rows[i].memberIdTo!=this.memberIdTo){
									// 代表对方对象
									this.memberBaseTo=res.data.rows[i].memberBase;
									break;
								}
							}
						} else {
							for (var i = 0; i < res.data.rows.length; i++) {
								this.dataList.unshift(res.data.rows[i]);
							}
							// 隐藏加载更多loading
							this.loadding = false;
						}
						// 如已是最后一条，则提示无加载更多
						console.log('this.dataList.length='+this.dataList.length);
						if (this.dataList.length >= res.data.total) {
							this.loadding = false;
							this.isNoMore=true;
						}
					} else {
						this.tui.toast('失败，' + res.msg);
					}
				})
				.catch(res => {
					console.log(res);
				});
		},
		openWebSocket(){
			let that=this;
			this.socketTask = uni.connectSocket({
			    url: this.$serverWss+this.tui.getToken(),
			    complete: ()=> {}
			});
			// 监听收到的消息
			this.socketTask.onMessage(function(data){
				console.log(JSON.stringify(data));
				let text=JSON.parse(data.data).contentText;
				that.dataList.push({content:text,memberIdTo:that.memberIdTo+'no',memberBase:that.memberBaseTo});
				uni.pageScrollTo({
					scrollTop: 90000000
				});
			});
			this.socketTask.onError(function(errMsg){
				console.log(JSON.stringify(errMsg));
			});
		},
		send(){
			if(this.inputValue==undefined || this.inputValue==''){
				this.tui.toast('内容不能为空');
				return;
			}
			// 判断是否有权限继续发送（3条对方未回复，不允许继续发送）
			this.checkAuthToSend({memberIdTo:this.memberIdTo});
		},
		sendByEnd(){
			let data='[{"toUserId":"'+this.memberIdTo+'","contentText":"'+this.inputValue+'"}]';
			this.socketTask.send({
				data:data,
				fail:(res)=> {
					this.tui.toast('发送失败');
				},
				success: (res) => {
					this.dataList.push({content:this.inputValue,memberIdTo:this.memberIdTo,memberBase:{headPic:this.headPic}});
					console.log('发送成功');
					this.inputValue='';
					uni.pageScrollTo({
						scrollTop: 90000000
					});
				}
			})
		},
		// 检查用户是否有权限发消息
		checkAuthToSend(postData){
			// let postData = { sign: this.newSign };
			this.tui
				.request('/auth/api/message/checkAuthToSend', postData, 'POST', false, true)
				.then(res => {
					if (res.code == 0) {
						if(res.data==1){
							this.sendByEnd();
						}else{
							this.tui.toast('对方未回复，不能继续发送哦');
						}
					}else{
						this.tui.toast(res.msg);
						return false;
					}
				})
				.catch(res => {
					console.log(res);
				});
		}
		},
		onUnload(){
			// 关闭socket
			this.socketTask.close({
				success: (res) => {
					console.log('关闭成功'+JSON.stringify(res));
				}
			})
		},
		onPageScroll(e) {
			console.log('this.dataList.length2='+this.dataList.length);
			if (this.isNoMore) return;
			if (e.scrollTop == 0 && !this.loadding) {
				this.loadding = true;
				this.pageData(++this.pageIndex, false,{memberIdTo:this.memberIdTo});
			}
		}
	}
</script>

<style>
	page {
		background: #ebedf6;
	}

	.container {
		padding-left: 20upx;
		padding-right: 20upx;
		padding-bottom: 146upx;
		box-sizing: border-box;
	}

	/*--tabbar--*/

	.tui-operation {
		width: 100%;
		height: 100upx;
		overflow: hidden;
		background: #EFF2FC;
		position: fixed;
		left: 0;
		bottom: 0;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-bottom: env(safe-area-inset-bottom);
		z-index: 999;
	}

	.tui-safearea-bottom {
		width: 100%;
		height: env(safe-area-inset-bottom);
	}

	.tui-operation::before {
		content: '';
		position: absolute;
		top: 0px;
		right: 0;
		left: 0;
		border-top: 1upx solid #eaeef1;
		-webkit-transform: scaleY(0.5);
		transform: scaleY(0.5);
	}

	.tui-chat-operation {
		background: #f6f6f6 !important;
		/* padding-right: 18upx; */
		/* box-sizing: border-box; */
	}
	.tui-pr{
		padding-right: 16rpx;
	}

	.tui-right-flex {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.tui-input-box {
		width: 80%;
		margin-left: 24rpx;
		justify-content: flex-start;
	}

	.tui-chat-input {
		background: #fff;
		height: 72upx;
		border-radius: 6upx;
		padding-left: 20upx;
		padding-right: 20upx;
		flex: 1;
	}

	

	.tui-opcity {
		opacity: 0.5;
	}

	/*--tabbar--*/

	/*chatbox*/
	.tui-chat-content {
		width: 100%;
		margin-bottom: 100upx;
	}

	.tui-chatbox {
		max-width: 66%;
		border-radius: 10upx;
		position: relative;
		padding: 20upx 22upx;
		font-size: 32upx;
		color: #000;
		/* text-align: justify; */
		word-break: break-all;
		word-wrap: break-word;
	}

	.tui-chatbox::before {
		content: "";
		position: absolute;
		width: 0;
		height: 0;
		top: 20upx;
		border: 16upx solid;
	}

	.tui-chatbox-left {
		background: #fff;
		border: 1upx solid #fff;
		display: inline-block;
	}

	.tui-chatbox-left::before {
		right: 100%;
		border-color: transparent #fff transparent transparent;
	}

	.tui-chatbox-right {
		background: #a0d5f3;
		border: 1upx solid #a0d5f3;
	}

	.tui-chatbox-right::before {
		left: 100%;
		border-color: transparent transparent transparent #a0d5f3;
	}


	/*chatbox*/

	.tui-chat-left,
	.tui-chat-right {
		display: flex;
		align-items: flex-start;
		padding-top: 36upx;
	}

	.tui-user-pic {
		width: 80upx;
		height: 80upx;
		flex-shrink: 0;
		border-radius: 50%;
		display: block;
	}

	.tui-left {
		margin-left: 26upx;
	}

	.tui-right {
		margin-right: 26upx;
	}

	.tui-chat-right {
		justify-content: flex-end;
	}

	.tui-chat-center {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 28upx;
		font-size: 28upx;
		color: #666;
		padding-top: 36upx;
	}

	.tui-label {
		display: inline-block;
		background: rgba(0, 0, 0, 0.4);
		color: #fff;
		font-size: 24upx;
		line-height: 24upx;
		margin-top: 36upx;
		padding: 12upx 16upx;
		text-align: center;
		border-radius: 8upx;
		margin-left: 50%;
		transform: translateX(-50%);
	}

	.tui-img-chatbox {
		position: relative;
	}

	.tui-img-chatbox::after {
		content: '';
		position: absolute;
		height: 200%;
		width: 200%;
		border: 1upx solid #eaeef1;
		transform-origin: 0 0;
		-webkit-transform-origin: 0 0;
		-webkit-transform: scale(0.5);
		transform: scale(0.5);
		left: 0;
		top: 0;
		border-radius: 20upx;
	}

	.tui-chat-img {
		max-width: 200upx;
		/* min-height: 80upx; */
		display: block;
		border-radius: 10upx;
	}

	.tui-chat-flex {
		display: flex;
		align-items: center;
	}

	.tui-flex-center {
		display: flex;
		align-items: center;
	}

	.tui-chat-voice {
		width: 40upx;
		height: 40upx;
		display: block;
		flex-shrink: 0;
	}

	.tui-rotate {
		transform: rotate(180deg)
	}

	.tui-chat-fail {
		width: 50upx;
		height: 50upx;
		display: block;
		flex-shrink: 0;
	}

	.tui-mr {
		margin-right: 16upx;
	}

	.tui-ml {
		margin-left: 16upx;
	}

	.tui-flex-end {
		justify-content: flex-end;
	}

	.tui-flex-reverse {
		flex-direction: row-reverse;
	}
</style>
